package com.foodorder.service;

import com.foodorder.entity.Product;
import com.foodorder.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品服务类
 */
@Service
@RequiredArgsConstructor
public class ProductService {
    
    private final ProductRepository productRepository;
    
    /**
     * 根据店铺ID查找商品
     */
    public List<Product> findByStoreId(Long storeId) {
        return productRepository.findByStoreIdAndStatus(storeId, Product.ProductStatus.AVAILABLE);
    }
    
    /**
     * 根据店铺ID和分类ID查找商品
     */
    public List<Product> findByStoreIdAndCategoryId(Long storeId, Long categoryId) {
        return productRepository.findByStoreIdAndCategoryIdAndStatus(storeId, categoryId, Product.ProductStatus.AVAILABLE);
    }
    
    /**
     * 根据店铺ID查找推荐商品
     */
    public List<Product> findRecommendedByStoreId(Long storeId) {
        return productRepository.findByStoreIdAndRecommendedAndStatus(storeId, true, Product.ProductStatus.AVAILABLE);
    }
    
    /**
     * 根据ID查找商品
     */
    public Product findById(Long id) {
        return productRepository.findById(id).orElse(null);
    }
    
    /**
     * 搜索商品
     */
    public Page<Product> searchProducts(String keyword, Pageable pageable) {
        return productRepository.searchProducts(keyword, pageable);
    }
    
    /**
     * 根据店铺ID按销量排序查找商品
     */
    public List<Product> findByStoreIdOrderBySales(Long storeId) {
        return productRepository.findByStoreIdAndStatusOrderByMonthlySalesDesc(storeId, Product.ProductStatus.AVAILABLE);
    }
    
    /**
     * 保存商品
     */
    public Product save(Product product) {
        return productRepository.save(product);
    }
    
    /**
     * 删除商品
     */
    public void deleteById(Long id) {
        productRepository.deleteById(id);
    }
    
    /**
     * 获取最近添加的商品
     */
    public List<Product> getRecentProducts(Long storeId, int days) {
        LocalDateTime since = LocalDateTime.now().minusDays(days);
        return productRepository.findByStoreIdAndCreatedAtAfterOrderByCreatedAtDesc(storeId, since);
    }
    
    /**
     * 更新商品库存
     */
    public void updateStock(Long productId, Integer quantity) {
        Product product = findById(productId);
        if (product != null) {
            product.setStock(product.getStock() - quantity);
            if (product.getStock() <= 0) {
                product.setStatus(Product.ProductStatus.SOLD_OUT);
            }
            save(product);
        }
    }
    
    /**
     * 增加商品销量
     */
    public void increaseSales(Long productId, Integer quantity) {
        Product product = findById(productId);
        if (product != null) {
            product.setMonthlySales(product.getMonthlySales() + quantity);
            save(product);
        }
    }
    
    /**
     * 管理端分页查询商品（支持多条件筛选）
     */
    public Page<Product> findProductsForAdmin(String keyword, String category, String status, Long storeId, Pageable pageable) {
        // 这里应该调用Repository的复杂查询方法，先简单实现
        if (keyword != null && !keyword.trim().isEmpty()) {
            return productRepository.searchProducts(keyword, pageable);
        } else if (storeId != null) {
            List<Product> products = productRepository.findByStoreId(storeId);
            // 简化处理，实际应该有更复杂的查询逻辑
            return new org.springframework.data.domain.PageImpl<>(products, pageable, products.size());
        } else {
            return productRepository.findAll(pageable);
        }
    }
    
    /**
     * 批量删除商品
     */
    public void deleteByIds(List<Long> ids) {
        productRepository.deleteAllById(ids);
    }
    
    /**
     * 更新商品状态
     */
    public void updateStatus(Long id, String status) {
        Product product = findById(id);
        if (product != null) {
            // 根据字符串状态设置枚举值
            switch (status.toLowerCase()) {
                case "active":
                case "available":
                    product.setStatus(Product.ProductStatus.AVAILABLE);
                    break;
                case "inactive":
                case "unavailable":
                    product.setStatus(Product.ProductStatus.UNAVAILABLE);
                    break;
                case "sold_out":
                    product.setStatus(Product.ProductStatus.SOLD_OUT);
                    break;
                default:
                    product.setStatus(Product.ProductStatus.UNAVAILABLE);
            }
            save(product);
        }
    }
    
    /**
     * 设置商品库存（用于管理端直接设置库存）
     */
    public void setStock(Long id, Integer stock) {
        Product product = findById(id);
        if (product != null) {
            product.setStock(stock);
            // 根据库存情况自动调整状态
            if (stock <= 0) {
                product.setStatus(Product.ProductStatus.SOLD_OUT);
            } else if (product.getStatus() == Product.ProductStatus.SOLD_OUT) {
                product.setStatus(Product.ProductStatus.AVAILABLE);
            }
            save(product);
        }
    }
} 